<template>
  <div v-if="visible" class="modal-overlay">
    <div class="register-modal" @click.stop>
      <div class="modal-header">
        <h3 class="modal-title">用户注册</h3>
        <button class="close-btn" @click="handleClose">&times;</button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="handleSubmitRegister" class="register-form">
          <!-- 姓名 -->
          <div class="form-group">
            <label for="registerUserName" class="form-label">姓名</label>
            <input
              type="text"
              id="registerUserName"
              v-model="registerForm.userName"
              class="form-input"
              :class="{ 'error': registerErrors.userName }"
              placeholder="请输入您的姓名"
            />
            <span v-if="registerErrors.userName" class="error-message">{{ registerErrors.userName }}</span>
          </div>

          <!-- 手机号 -->
          <div class="form-group">
            <label for="registerUser" class="form-label">手机号</label>
            <input
              type="tel"
              id="registerUser"
              v-model="registerForm.user"
              class="form-input"
              :class="{ 'error': registerErrors.user }"
              placeholder="请输入手机号码"
            />
            <span v-if="registerErrors.user" class="error-message">{{ registerErrors.user }}</span>
          </div>

          <!-- 密码 -->
          <div class="form-group">
            <label for="registerPwd" class="form-label">密码</label>
            <input
              type="password"
              id="registerPwd"
              v-model="registerForm.pwd"
              class="form-input"
              :class="{ 'error': registerErrors.pwd }"
              placeholder="请输入密码，至少6位"
            />
            <span v-if="registerErrors.pwd" class="error-message">{{ registerErrors.pwd }}</span>
          </div>

          <!-- 确认密码 -->
          <div class="form-group">
            <label for="confirmPassword" class="form-label">确认密码</label>
            <input
              type="password"
              id="confirmPassword"
              v-model="registerForm.confirmPassword"
              class="form-input"
              :class="{ 'error': registerErrors.confirmPassword }"
              placeholder="请再次输入密码"
            />
            <span v-if="registerErrors.confirmPassword" class="error-message">{{ registerErrors.confirmPassword }}</span>
          </div>
        </form>
      </div>

      <div class="modal-footer">
        <button class="btn-cancel" @click="handleClose">取消</button>
        <button 
          class="btn-confirm" 
          @click="handleSubmitRegister"
          :disabled="isLoading"
        >
          <span v-if="isLoading">注册中...</span>
          <span v-else>立即注册</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { register } from '@/api/home'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  }
})

// Events
const emit = defineEmits(['close', 'register-success'])

// 数据
const isLoading = ref(false)

// 注册表单数据 - 直接匹配后端DTO字段
const registerForm = reactive({
  userName: '',        // 对应后端 userName
  user: '',           // 对应后端 user (手机号)
  pwd: '',            // 对应后端 pwd
  confirmPassword: '' // 仅前端验证用
})

const registerErrors = reactive({
  userName: '',
  user: '',
  pwd: '',
  confirmPassword: ''
})

// 验证注册表单
const validateRegisterForm = () => {
  let isValid = true
  
  // 重置错误信息
  registerErrors.userName = ''
  registerErrors.user = ''
  registerErrors.pwd = ''
  registerErrors.confirmPassword = ''
  
  // 验证姓名
  if (!registerForm.userName.trim()) {
    registerErrors.userName = '请输入姓名'
    isValid = false
  } else if (registerForm.userName.length < 2) {
    registerErrors.userName = '姓名至少需要2个字符'
    isValid = false
  }
  
  // 验证手机号
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!registerForm.user.trim()) {
    registerErrors.user = '请输入手机号码'
    isValid = false
  } else if (!phoneRegex.test(registerForm.user)) {
    registerErrors.user = '请输入正确的手机号码格式'
    isValid = false
  }
  
  // 验证密码
  if (!registerForm.pwd) {
    registerErrors.pwd = '请输入密码'
    isValid = false
  } else if (registerForm.pwd.length < 6) {
    registerErrors.pwd = '密码至少需要6位字符'
    isValid = false
  }
  
  // 验证确认密码
  if (!registerForm.confirmPassword) {
    registerErrors.confirmPassword = '请确认密码'
    isValid = false
  } else if (registerForm.pwd !== registerForm.confirmPassword) {
    registerErrors.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }
  
  return isValid
}

// 提交注册
const handleSubmitRegister = async () => {
  if (!validateRegisterForm()) {
    return
  }
  
  isLoading.value = true
  try {
    // 直接调用注册API，字段名已匹配后端DTO
    const { confirmPassword, ...registerData } = registerForm
    const response = await register(registerData)
    
    ElMessage.success('注册成功！')
    
    // 通知父组件注册成功
    emit('register-success', response)
    
    // 重置表单并关闭
    resetForm()
    
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error('注册失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 关闭模态框
const handleClose = () => {
  resetForm()
  emit('close')
}

// 重置表单
const resetForm = () => {
  registerForm.userName = ''
  registerForm.user = ''
  registerForm.pwd = ''
  registerForm.confirmPassword = ''
  
  registerErrors.userName = ''
  registerErrors.user = ''
  registerErrors.pwd = ''
  registerErrors.confirmPassword = ''
}

// 暴露方法给父组件
defineExpose({
  resetForm
})
</script>

<style scoped>
/* 模态框 */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.register-modal {
  background: white;
  border-radius: 15px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  color: #333;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 1px solid #eee;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  cursor: pointer;
  color: #999;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
  padding: 0;
  line-height: 1;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
  transform: scale(1.1);
}

.modal-body {
  padding: 25px;
}

/* 表单样式 */
.register-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.form-input {
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #3742fa;
  box-shadow: 0 0 0 2px rgba(55, 66, 250, 0.1);
}

.form-input.error {
  border-color: #ff4757;
  box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.1);
}

.error-message {
  font-size: 12px;
  color: #ff4757;
  margin-top: 4px;
}

.modal-footer {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  padding: 20px 25px;
  border-top: 1px solid #eee;
  background: #f8f9fa;
}

.btn-cancel {
  padding: 10px 20px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid;
  background: #f5f5f5;
  color: #666;
}

.btn-confirm {
  padding: 10px 20px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid;
  background: #3742fa;
  color: white;
}

.btn-confirm:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>
